package com.school.basic.service.impl;

import com.school.basic.entity.SchoolInfo;
import com.school.basic.entity.TeacherInfo;
import com.school.basic.repository.SchoolInfoRepository;
import com.school.basic.repository.TeacherInfoRepository;
import com.school.basic.service.TeacherInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class TeacherInfoServiceImp implements TeacherInfoService {
    @Autowired
    TeacherInfoRepository teacherInfoRepository;
    @Autowired
    SchoolInfoRepository schoolInfoRepository;

    /**
     * 增加
     * @param teacherInfo
     * @return
     */
    @Override
    public TeacherInfo addTeacherInfo(TeacherInfo teacherInfo) {
        teacherInfo.setCreateDate(new Date());
        teacherInfo.setUpdateDate(new Date());
        return teacherInfoRepository.saveAndFlush(teacherInfo);
    }

    /**
     * 查询所有
     * @param
     */
    @Override
    public List<TeacherInfo> findAll() {
        return teacherInfoRepository.findAll();
    }

    /**
     * 状态更新
     * @param id,status
     */
    @Override
    public void updateStatus(String id,Integer status) {
        TeacherInfo teacherInfo;
        try {
            teacherInfo = teacherInfoRepository.findById(Integer.valueOf(id)).get();
            teacherInfo.setStatus(status);
            teacherInfoRepository.saveAndFlush(teacherInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改
     * @param teacherInfo
     * @return
     */
    @Override
    public TeacherInfo updateTeacherInfo(TeacherInfo teacherInfo) {
        teacherInfo.setUpdateDate(new Date());
        return teacherInfoRepository.saveAndFlush(teacherInfo);
    }

    /**
     * 查看详情
     * @param id
     */
    @Override
    public TeacherInfo getDetailsById(String id) {
        return teacherInfoRepository.findById(Integer.valueOf(id)).get();
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteTeacherInfo(String id) {
        TeacherInfo teacherInfo;
        try {
            teacherInfo = teacherInfoRepository.findById(Integer.valueOf(id)).get();
            teacherInfoRepository.delete(teacherInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除
     * @param idList
     */
    @Override
    public void deleteTeacherInfoList(String idList) {
        String[] split = idList.split(",");
        List<Integer> list = new ArrayList<>();
        for (String s : split) {
            list.add(Integer.parseInt(s));
        }
        teacherInfoRepository.deleteTeacherInfosByIdIn(list);
    }

    /**
     * 根据条件分页查询
     * @param teacherInfo,page,size
     */
    @Override
    public Page<TeacherInfo> specificPageQueryTeacherInfoList(TeacherInfo teacherInfo, int page, int size) {
        Specification querySpecification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(teacherInfo != null)
                {
                    Integer status = teacherInfo.getStatus();
                    Integer isHeadteacher = teacherInfo.getIsHeadteacher();
                    String name = teacherInfo.getName();
                    if (status != null)
                    {
                        predicates.add(criteriaBuilder.equal(root.get("status").as(Integer.class),status));
                    }
                    if (isHeadteacher != null)
                    {
                        predicates.add(criteriaBuilder.equal(root.get("isHeadteacher").as(Integer.class),isHeadteacher));
                    }
                    if (!StringUtils.isEmpty(name))
                    {
                        predicates.add(criteriaBuilder.like(root.get("name").as(String.class),'%' + name + '%'));
                    }
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        List<TeacherInfo> teacherInfoList = teacherInfoRepository.findAll(querySpecification);
        for(int i = 0; i < teacherInfoList.size(); i ++){
            Integer schoolId = teacherInfoList.get(i).getSchoolId();
            if(schoolId != null){
                SchoolInfo schoolInfo = schoolInfoRepository.findById(schoolId).get();
                if(schoolInfo != null){
                    if(!StringUtils.isEmpty(schoolInfo.getSchoolName())){
                        teacherInfoList.get(i).setSchoolName(schoolInfo.getSchoolName());
                    }
                }
            }
        }
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC,"updateDate"));
        // 当前页第一条数据在List中的位置
        int start = (int)pageRequest.getOffset();
        // 当前页最后一条数据在List中的位置
        int end = (start + pageRequest.getPageSize()) > teacherInfoList.size() ? teacherInfoList.size() : ( start + pageRequest.getPageSize());
        // 配置分页数据
        return new PageImpl<TeacherInfo>(teacherInfoList.subList(start, end), pageRequest, teacherInfoList.size());
    }

    /**
     * 根据学校ID查询所有
     * @param schoolId
     */
    @Override
    public List<TeacherInfo> findAllBySchoolId(Integer schoolId){
        return teacherInfoRepository.findAllBySchoolId(schoolId);
    }

    @Override
    public TeacherInfo findTeacherByAccountAndPassword(Integer account, String password) {
        TeacherInfo teacherInfo = new TeacherInfo();
        teacherInfo.setAccount(account);
        teacherInfo.setPassword(password);
        Optional<TeacherInfo> one = teacherInfoRepository.findOne(Example.of(teacherInfo));
        teacherInfo = null;
        return one.orElse(null);
    }
}
